package com.zihan.task;

import com.zihan.domain.entity.Project;
import com.zihan.domain.entity.ProjectInvitation;
import com.zihan.domain.entity.ProjectMilestone;
import com.zihan.service.IProjectInvitationService;
import com.zihan.service.IProjectMilestoneService;
import com.zihan.service.IProjectService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class CheckProjectStatus {


    @Resource
    private IProjectService projectService;
    @Resource
    private IProjectMilestoneService projectMilestoneService;
    @Resource
    private IProjectInvitationService projectInvitationService;

    @Scheduled(cron = "0 * * * * ?")
    private void checkProjectStatus() {
        log.info("开始检查项目状态");
        // 获取所有状态为0或者1的项目
        List<Project> projectList = projectService.lambdaQuery().eq(Project::getStatus, 0).or().eq(Project::getStatus, 1)
                .list();

        // 获取所有项目（包括已结束的）
        for (Project project : projectList) {
            Integer currentStatus = project.getStatus();
            Integer newStatus = calculateStatus(project.getStartDate(), project.getEndDate());

            // 如果状态发生变化，则更新
            if (newStatus != null && !newStatus.equals(currentStatus)) {
                project.setStatus(newStatus);
                projectService.updateById(project);
                log.info("项目 {} 状态已从 {} 更新为 {}", project.getId(), currentStatus, newStatus);
            }
        }
    }


    @Scheduled(cron = "0 * * * * ?")
    private void checkProjectMilestoneStatus() {
        log.info("开始检查项目状态");
        // 获取所有状态为0或者1的项目
        List<ProjectMilestone> projectList = projectMilestoneService.lambdaQuery()
                            .eq(ProjectMilestone::getStatus, 0).or().eq(ProjectMilestone::getStatus, 1)
                            .list();
        // 获取所有项目（包括已结束的）
        for (ProjectMilestone project : projectList) {
            Integer currentStatus = project.getStatus();
            Integer newStatus = calculateStatus(project.getStartDate(), project.getEndDate());
            // 如果状态发生变化，则更新
            if (newStatus != null && !newStatus.equals(currentStatus)) {
                project.setStatus(newStatus);
                projectMilestoneService.updateById(project);
                log.info("项目 {} 状态已从 {} 更新为 {}", project.getId(), currentStatus, newStatus);
            }
        }
    }


    /**
     * 检查检查邀请是否过期了
     * @param startDate
     * @param endDate
     * @return
     */
    @Scheduled(cron = "0 * * * * ?")
    private void checkInviteExpired() {
        log.info("开始检查邀请是否过期");
        // 获取所有状态为0或者1的项目
        List<ProjectInvitation> list = projectInvitationService.lambdaQuery().eq(ProjectInvitation::getStatus, 0)
                .le(ProjectInvitation::getExpireTime, LocalDateTime.now())
                .list();
        if (list.isEmpty()) {
            // 批量修改状态
            list.stream().forEach(invitation -> {
                invitation.setStatus(4);
            });
            projectInvitationService.updateBatchById(list);
        }
    }


    private Integer calculateStatus(LocalDate startDate, LocalDate endDate) {
        if (startDate == null || endDate == null) {
            return null;
        }
        LocalDate now = LocalDate.now();
        if (now.isBefore(startDate)) {
            return 0; // 未开始
        } else if (now.isAfter(endDate)) {
            return 2; // 已结束
        } else {
            return 1; // 进行中
        }
    }
}
